package com.handler.email;

import com.domain.ex.BizException;
import com.domain.ex.Codes;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Huoyunren on 2016/2/15.
 */
public class EmailHandler {

    private static final Logger LOG = LoggerFactory.getLogger(EmailHandler.class);

    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private SimpleMailMessage simpleMailMessage;
    @Autowired
    private FreeMarkerConfigurer freeMarker;

    /**
     * 发送简单邮件
     *
     * @param email
     */
    private void sendMail(Email email) {
        if (email == null || email.getTo() == null || email.getTo().length == 0) {
            return;
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
            // - 设置发件人昵称
            String nick = javax.mail.internet.MimeUtility.encodeText("劉員外","UTF-8",null);
            String from = simpleMailMessage.getFrom();
            messageHelper.setFrom(new InternetAddress(from, nick));
            messageHelper.setTo(email.getTo());
            messageHelper.setSubject(email.getSubject());
            messageHelper.setText(processEmailText(email), email.getEnableHtml());
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw BizException.create(Codes.SystemError, e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw BizException.create(Codes.SystemError, e.getMessage());
        }
    }

    private String processEmailText(Email email) {
        String text = "";
        if (email == null) {
            return text;
        }
        if (!email.getEnableHtml()) {
            // - 不使用模板
            text = email.getContent();
        } else {
            try {
                Template template = freeMarker.getConfiguration().getTemplate(email.getTemplate());
                text = FreeMarkerTemplateUtils.processTemplateIntoString(template, email.getMap());
            } catch (IOException e) {
                throw BizException.create(Codes.SystemError, "发送模板邮件异常：" + e.getMessage());
            } catch (TemplateException e) {
                throw BizException.create(Codes.SystemError, "发送模板邮件异常：" + e.getMessage());
            }
        }
        return text;
    }


    /**
     * 异步发送简单邮件
     *
     * @param email
     */
    public void asyncSendMail(final Email email) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                sendMail(email);
            }
        });
    }

}
